var app = getApp();
var api = require('./api.js');
var md5 = require('./md5.js');

// 判断一个月有几天
function getDaysInOneMonth(year, month){
    month = parseInt(month, 10);
    var day= new Date(year, month, 0);
    return day.getDate();
}

function picupload(success){
	var token = uni.getStorageSync('token')
	var url = api.apis.uploadimage + '&wxapp_id=10001&token='+token
	uni.chooseImage({
		count: 1, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], //从相册选择
		success: (res) => {
            console.log(res)
			uni.uploadFile({
			    url: url, //服务器地址
			    fileType: "image", //ZFB必填,不然报错
			    filePath:res.tempFilePaths[0], //这个就是我们上面拍照返回或者先中照片返回的数组
			    name: 'iFile',
			    success: (res) => {
			        success && success(res)
			    }
			});

		}
	});
}



function getstrletter (str) {

}

//提示信息
function showErrorToast(msg) {
	uni.showToast({
		title: msg,
		icon: 'none'
	})
}
/**
 *手机掩码
 * @param {Object} phone
 */
function phoneMask(phone) {
	return phone.substring(0, 3) + '****' + phone.substring(7);
}
/**
 * 验证手机号
 * @param {Object} phone
 */
function checkPhone(phone) {
	let zz = /^1[3456789]\d{9}$/;
	return zz.test(phone);
}
/**
 * 验证姓名
 * @param {Object} phone
 */
function checkName(name) {
	let zz = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/; //验证姓名正则
	return zz.test(name);
}
//验证日期
function checkDate(date) {
	let shengri_zz = /^\d{4}-\d{2}-\d{2}$/; //日期验证
	return shengri_zz.test(date);
}

//检验密码
function validatePhonePass(pass) {
	let  passRegex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,30}$/; //检验密码
	return  passRegex.test(pass)

}


/**
 * 显示加载框
 */
function myLoading(msg = '加载中') {
	uni.showLoading({
		title: msg,
		mask: false,
	});
}
/**
 *  弹出提示信息
 */
function showMsg(msg, duration = 2000, callback) {
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: duration,
		success: function() {
			setTimeout(callback, duration);
		}
	})
}
/**
 * request
 */
function request(url, data = {}, method = "GET",header = {'content-type':'application/json','Authorization': 'Basic cmVucmVuaW86cmVucmVuaW8='}) {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success(res) {
				resolve(res.data);
			},
			fail(err) {
				// console.log(err)
				reject(err)
			}
		})
	});
}

/**
 *  登录后的request请求
 */
function loggedrequest(url, data = {}, method = "GET",header = {'content-type':'application/json'}) {
	return new Promise(function(resolve, reject) {
		uni.showLoading({
		    title:"加载中..."
		})
		let token = ''
		uni.getStorage({
		    key: 'token',
		    success: function (res) {
		        //console.log(res.data);
				token = res.data
				//console.log(token);
				if(token==''){
					//util.showMsg('请先登录')
					util.showMsg("请先登录!", 1000, function() {
						uni.navigateTo({
							// url: "/pages/register/register",
							url: "/pages/register/login",
						})
					})
					uni.navigateTo({
						// url: "/pages/register/register",
						url: "/pages/register/login",
					})
				}else{
					//header.wxapp_id = "10001"
					uni.request({
						url: url+'&wxapp_id=10001&token='+token,
						data: data,
						method: method,
						header: header,
						success(res) {
                            uni.hideLoading()
							resolve(res.data);
						},
						fail(err) {
							// console.log(err)
							reject(err)
						}
					})
				}
		    },
			fail(err) {
				//util.showMsg('  请先登录')
				uni.navigateTo({
					// url: "/pages/register/register",
					url: "/pages/register/login",
				})
			}
		});

	});
}

/**
 * 跳转到登录页面,并清空缓存
 */
function toLogin(e) {
	// this.myHideLoading();
	uni.hideLoading()
	uni.clearStorage();
	// 关闭WebSocket
	// if(e=='true'){
	// 	uni.reLaunch({
	// 		url: "/pages/register/register"
	// 	})
	// }else{

	// }
	uni.navigateTo({
		// url: "/pages/register/register",
		url: "/pages/sl_login/login.vue",
	})
}
/**
 * 对象转url参数
 * @param {Object} obj
 */
function objToUrl(obj) {
	let u = "";
	for (let key in obj) {
		u = u + key + "=" + obj[key] + "&";
	}
	return u.substring(0, u.length - 1);
}
/**
 * 登录后的网络请求
 */
// function myrequest(url, data = {}, method = "GET",header = {'content-type':'application/json'}) {
// 	let that = this;
// 	return new Promise((resolve, reject) => {
//         header.Authorization = 'Bearer ' + '1ad62a56-b1af-4104-bd73-ec20370d8211';
// 		that.request(
// 			url,
// 			data,
// 			method,
// 			header
// 		).then(res => {
// 		    console.log(res)
// 			if (res.code == 401) {
// 				// that.showErrorToast("签名错误,即将退出登录!")
// 				console.log('签名错误');
// 				that.toLogin();
// 			} else {
// 				resolve(res);
// 			}
// 		}).catch(err => {
// 			resolve({
// 				code: 1,
// 				msg: err.errMsg
// 			});
// 		});
//   //       uni.getStorage({
// 		// 	key: "token",
// 		// 	success: function(e) {
// 		// 		header.Authorization = 'Bearer' + e.data;
// 		// 		//发起请求
				
// 		// 	},
// 		// 	fail: function() {
// 		// 		// 重新登录
// 		// 		that.toLogin();
// 		// 	}
// 		// })
// 	});
// }
function myrequest(
  url,
  data = {},
  method = "GET",
  header = { "content-type": "application/json" }
) {
  let that = this;
  //发起请求
  return new Promise((resolve, reject) => {
    uni.getStorage({
      key: "token",
      success: function (e) {
        header.Authorization = "Bearer " + e.data;
        that
          .request(url, data, method, header)
          .then((res) => {
            // console.log(res);
            if (res.code == 401) {
              // that.showErrorToast("签名错误,即将退出登录!")
              // // console.log("签名错误");
              that.toLogin();
            } else {
              resolve(res);
            }
          })
          .catch((err) => {
            reject({
              code: 1,
              msg: err.errMsg,
            });
          });
      },
      fail: function () {
        // 重新登录
        that.toLogin();
      },
    });
  });
}
// function myrequest(url, data = {}, method = "GET",header = {'content-type':'application/json'}) {
// 	let that = this;
// 	//进行签名加密
// 	let time = Date.parse(new Date()) / 1000;
// 	let can = '';
// 	if (method == "GET") {
// 		can = that.objToUrl(data);
// 		url = url + "?" + can;
// 	}

// 	return new Promise((resolve, reject) => {
// 		uni.getStorage({
// 			key: "user_info",
// 			success: function(e) {
// 				let id = e.data.user_id;
// 				let token = e.data.token;
// 				let sign = md5(id + "" + time + "" + token);
// 				// console.log(id+'**'+time+'**'+token);

// 				data.uid = id;
// 				// data.token = token;
// 				data.time = time;
// 				data.sign = sign;
// 				//发起请求
// 				that.request(
// 					url,
// 					data,
// 					method
// 				).then(res => {
// 					if (res.code == 4001) {
// 						// that.showErrorToast("签名错误,即将退出登录!")
// 						console.log('签名错误');
// 						that.toLogin();
// 					} else {
// 						resolve(res);
// 					}
// 				}).catch(err => {
// 					resolve({
// 						code: 1,
// 						msg: err.errMsg
// 					});
// 				});
// 			},
// 			fail: function() {
// 				// resolve({
// 				// 	code:1,
// 				// 	msg:"用户信息获取失败,请重新登录!"
// 				// });
// 				// this.showErrorToast('用户信息获取失败!');
// 				// setTimeout(function(){
// 				// that.toLogin();
// 				// },1000);
// 			}
// 		})
// 	});
// }
/**
 * 获取用户全面信息
 */
function getUserInfoAll() {
	let that = this;
	return new Promise((resolve, reject) => {
		this.myrequest(
			api.apis.index, {}
		).then(res => {
			if (res.code == 0) {
				resolve(res);
			} else if (res.code == 4002) {
				console.log("用户不存在");
				util.showMsg("用户不存在!", 1000, function() {
					that.toLogin();
				})
			}
		})
	});
}
/**
 * 检查是否已登录
 */
function checkLogin() {
	let that = this;
	let user_info = uni.getStorageSync('user_info');
	if (user_info != "") {
		if (user_info.token.length <= 0 || user_info.user_id <= 0) {
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
}
/**
 * 获取接口加密信息
 */
function getLoginSign() {
	let time = Date.parse(new Date()) / 1000;
	let value = uni.getStorageSync('user_info');
	let data = {};
	if (value) {
		let id = value.user_id;
		let token = value.token;
		let sign = md5(id + "" + time + "" + token);
		data.uid = id;
		data.time = time;
		data.sign = sign;
		return data;
	}
	return data;
}
/**
 *  退出登录
 */
function logout() {
	let that = this;
	uni.showModal({
		title: '提示',
		content: '确定退出吗?',
		success: function(res) {
			if (res.confirm) {
				//清空缓存
				that.toLogin();
				// 关闭WebSocket
				uni.closeSocket();
			} else if (res.cancel) {
				// console.log('用户点击取消');
			}
		}
	});
}
// 时间戳转日期
function formatDate(unixtimestamp) {
	var unixtimestamp = new Date(unixtimestamp * 1000);
	var year = 1900 + unixtimestamp.getYear();
	var month = "0" + (unixtimestamp.getMonth() + 1);
	var date = "0" + unixtimestamp.getDate();
	var hour = "0" + unixtimestamp.getHours();
	var minute = "0" + unixtimestamp.getMinutes();
	var second = "0" + unixtimestamp.getSeconds();
	return year + "-" + month.substring(month.length - 2, month.length) + "-" + date.substring(date.length - 2, date.length)
	// + " " + hour.substring(hour.length-2, hour.length) + ":"
	// + minute.substring(minute.length-2, minute.length) + ":"
	// + second.substring(second.length-2, second.length);
}
// 检查是否实名
// function authStatus(){
// 	this.getUserInfoAll().then(res=>{
// 		if(res.code==0){
// 			if(res.data.auth_status!=1){
// 				util.showErrorToast(res.msg);
// 			}
// 		}else{
// 			util.showErrorToast(res.msg);
// 		}
// 	})
// }
//连接websocket
function websocket() {
	let _this = this;
	let uid = '';
	let sign = _this.getLoginSign();
	let randomId = uni.getStorageSync('randomId');
	if (_this.checkLogin()) {
		uid = sign.uid;
	} else {
		uid = randomId.uid;
	}
	uni.connectSocket({
		url: 'ws://110.249.169.182:9502?app=rescueAppAnd&str=ddfe&sign=49ba59abbe56e057&uid=' + uid
	});

	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！');
		uni.setStorageSync('socket', {
			state: true
		});
		uni.setStorageSync('socket_num', {
			num: 0
		});
		let msg = ''
		setInterval(function() {
			let socket = uni.getStorageSync('socket');
			if (socket.state == true) {
				uni.sendSocketMessage({
					data: msg,
					success(res) {}
				});
			}
		}, 30000);
	});
	uni.onSocketError(function(res) {
		console.log('WebSocket连接打开失败，请检查！');
		_this.socketFail();
	});
	uni.onSocketMessage(function(res) {
		console.log('收到服务器内容：' + res.data);

		let data = JSON.parse(res.data);
		console.log(data)
		if (data.type == 'carReply') {
			uni.showModal({
				title: '通知',
				content: '您的车险报价已完成',
				confirmText: '立即查看',
				success: function(res) {
					if (res.confirm) {
						console.log("立即查看")
						uni.navigateTo({
							url: '/pages/car_offer/car_offer?basics=1'
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		} else {
			uni.showModal({
				title: '通知',
				content: data.msg,
				success: function(res) {}
			});
		}
	});
	uni.onSocketClose(function(res) {
		console.log('WebSocket 已关闭！')
		_this.socketFail();
	});
}
// websocket关闭时重连
function socketConnect() {
	let _this = this;
	let socket = uni.getStorageSync('socket')
	if (socket.state != true) {
		uni.setStorageSync('socket_num', {
			num: 0
		});
		_this.websocket();
	}
}
// 断开重连
function socketFail() {
	let _this = this;
	uni.setStorageSync('socket', {
		state: false
	});
	let socket_num = uni.getStorageSync('socket_num');
	let numadd = socket_num.num + 1
	uni.setStorageSync('socket_num', {
		num: numadd
	});
	let new_num = uni.getStorageSync('socket_num');
	console.log(numadd)
	if (new_num.num < 5) {
		_this.websocket();
	}
}
//登录弹窗提示
function LoginShowModal() {
	let that = this
	uni.showModal({
		title: '提示',
		content: '您还没有登录',
		confirmText: '立即登录',
		success: function(res) {
			if (res.confirm) {
				that.toLogin();
			} else if (res.cancel) {
				// console.log('用户点击取消');
			}
		}
	});
}
//生成时间戳+随机数缓存及socket失败次数
function randomId() {
	let num = Math.floor(Math.random() * 100000 + 1);
	let time = parseInt(new Date().getTime());
	let Id = md5(num + time);
	uni.setStorageSync('randomId', {
		uid: Id
	});
	uni.setStorageSync('socket_num', {
		num: 0
	});
}

// 数字变中文
function numchanggechina(num){
	let str = num.toString()
	let arrChina = ["零","一","二","三","四","五","六","七","八","九"]
	let weight = ['',"十","百","千","万"]
	let strarr = str.split("")
		strarr = strarr.map(t =>{
			var num = parseInt(t)
			console.log(num)
			return  arrChina[num]
		})
	console.log(strarr)

}

// 成唯一标识符UUID
function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

module.exports = {
	picupload,
	showErrorToast,
	checkPhone,
	myLoading,
	showMsg,
	checkDate,
	loggedrequest,
	myrequest,
	request,
	objToUrl,
	getUserInfoAll,
	phoneMask,
	checkLogin,
	getLoginSign,
	logout,
	toLogin,
	checkName,
	formatDate,
	socketConnect,
	LoginShowModal,
	websocket,
	randomId,
	socketFail,
	numchanggechina,
	validatePhonePass,
	generateUUID,

}
